package com.example.mysimpleexample.custom_component;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.example.mysimpleexample.R;

import org.jetbrains.annotations.NotNull;

public class CountDownText extends AppCompatTextView {
    private CountDownTimer mCountDownTimer;
    //持续时间毫秒
    private int mTimeDuration;
    //间隔时间毫秒
    private int mTimerCap;

    public CountDownText(@NonNull @NotNull Context context) {
        this(context,null);
    }

    public CountDownText(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CountDownText(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountDownText);
        mTimeDuration = typedArray.getInt(R.styleable.CountDownText_millisDuration,6000);
        mTimerCap = typedArray.getInt(R.styleable.CountDownText_millisGap,1000);
        Log.e("d",Integer.toString(mTimeDuration));
        Log.e("a",Integer.toString(mTimerCap));
        typedArray.recycle();
        initTimer();
        setText("获取验证码");

    }

    private void initTimer() {
        mCountDownTimer = new CountDownTimer(mTimeDuration + 500,mTimerCap) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.e("r",String.format("%ss后重新获取",millisUntilFinished / 1000));
                setText(String.format("%ss后重新获取",millisUntilFinished / 1000));
                setEnabled(false);
                setTextColor(Color.parseColor("#333333"));
            }

            @Override
            public void onFinish() {
                setEnabled(true);
                setText("重新获取");
                setTextColor(Color.parseColor("#ff0000"));
            }
        };
    }

    public void start(){
        if (mCountDownTimer != null) {
            mCountDownTimer.start();
        }
    }

    public void end(){
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        end();
        mCountDownTimer = null;
    }
}
